package simulation;

import java.io.FileOutputStream;
import java.io.PrintStream;

import streaming.Host;
import streaming.Overlay;
import streaming.StreamingConfig;

public class PeriodicStats implements EventHandler {

	Simulator sim;
	Overlay overlay;
	double interval = StreamingConfig.MCASTUPDATEINTERVAL;
	PrintStream out;

	FullStatistics downloadStats = new FullStatistics();
	FullStatistics uploadStats = new FullStatistics();
	
	public PeriodicStats() {
		try {
			String filename = "simulationStatistics.csv";
			out = new PrintStream(new FileOutputStream(filename));

			overlay = Overlay.getInstance();
			sim = Simulator.getInstance();
		} catch (Exception e) {
			System.out.println("Problems with periodic stats: "
					+ e.getMessage());
		}
	}

	public void addEvent() {
		double time = sim.getTime() + interval;
		if (Math.abs(time - Math.round(time)) < 0.00001)
			time = Math.round(time);
		time -= 0.000001; // Make sure this is executed before updates of every
							// node
		sim.addEvent(time, this);
	}

	public void stop() {
		out.flush();
		out.close();
	}

	public void run(double time) {
		Host[] hosts = overlay.getHosts();
		int partialSum = 0;
		for (int i = 0; i < hosts.length; i++) {
			downloadStats.add(hosts[i].getPrevReceivedCount());
			partialSum += hosts[i].getPrevReceivedCount();
			// uploadStats.add(hosts[i].prevSentCount);
		}
		out.print(time + 0.000001 + "," + hosts.length + "," + partialSum);
//		System.out.println(downloadStats.sum());
		downloadStats.dump(out);
		out.println();
		// uploadStats.dump(out);
		// out.println();
		downloadStats = new FullStatistics();
		uploadStats = new FullStatistics();
		addEvent();
	}
}